<template>
  <div title="文本颜色" class="tlbr-btn hm">
    <div class="tlbr-btn__icon" :style="{ color: color }">
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <rect
          x="4"
          y="18.5"
          width="16"
          height="2"
          rx="1"
          fill="currentColor"
        ></rect>
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M12.279 4.74032C12.1775 4.5288 11.9619 4.39589 11.7273 4.40012C11.4927 4.40435 11.2821 4.54495 11.1883 4.75999L5.95016 16.76C5.81759 17.0637 5.95632 17.4174 6.26002 17.5499C6.56372 17.6825 6.91738 17.5438 7.04995 17.2401L9.119 12.5H14.4C14.4885 12.5 14.5725 12.4809 14.6481 12.4465L16.9592 17.2597C17.1026 17.5585 17.461 17.6843 17.7598 17.5409C18.0585 17.3975 18.1844 17.039 18.0409 16.7403L12.279 4.74032ZM14.0976 11.3L11.7641 6.4403L9.64281 11.3H14.0976Z"
          fill="#18191C"
        ></path>
      </svg>
    </div>
    <svg
      width="4"
      height="4"
      viewBox="0 0 4 4"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      class="tlbr-btn__dot"
    >
      <path d="M4 0V4H0L4 0Z" fill="#222222"></path>
    </svg>
    <div class="tlbr-btn__more">
      <div class="tlbr-btn__more__tooltip">
        <div class="bre-toolbar__colorpicker">
          <div class="bre-toolbar__colorpicker__ceiling">
            <div
              class="bre-toolbar__colorpicker__tile"
              :class="{ active: color === defaultColorConfig.backgroundColor }"
              style="background-color: rgb(47, 50, 56)"
              @click="changeColor(defaultColorConfig)"
            ></div>
            <div style="margin-left: 5px">默认颜色</div>
          </div>
          <div
            class="bre-toolbar__colorpicker__ceiling"
            v-show="usedColorList.length > 0"
          >
            <div style="width: 100%; text-align: left; margin-bottom: 3px">
              最近使用
            </div>
            <div
              class="bre-toolbar__colorpicker__tile"
              :style="{
                backgroundColor: item.backgroundColor,
                borderColor: item.borderColor,
              }"
              v-for="(item, index) in usedColorList"
              :key="index"
              @click="changeColor(item)"
            ></div>
          </div>
          <div class="bre-toolbar__colorpicker__ceiling">
            <div
              class="bre-toolbar__colorpicker__tile"
              :style="{
                backgroundColor: item.backgroundColor,
                borderColor: item.borderColor,
              }"
              v-for="(item, index) in colorConfigList"
              :key="index"
              @click="changeColor(item)"
            ></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, inject, shallowRef } from 'vue'
import Quill, { StringMap } from 'quill'
import { hexToRgb } from '../../utils'
const QuillEditor = inject('QuillEditor', shallowRef<Quill>())
const formatMap = inject('formatMap', ref<Record<string, any>>({}))
const Delta = Quill.import('delta')

const getSelectionFormat = inject('getSelectionFormat', () => {})
interface ColorConfig {
  backgroundColor: string
  borderColor?: string
}
// 默认颜色配置
const defaultColorConfig: ColorConfig = {
  backgroundColor: 'rgb(47,50,56)',
}
//最近使用列表
const usedColorList = reactive<ColorConfig[]>([
  { backgroundColor: 'rgb(137,250,78)', borderColor: 'rgb(116,213,67)' },
])
//颜色配置列表
const colorConfigList = reactive<ColorConfig[]>([
  { backgroundColor: 'rgb(137,212,255)', borderColor: 'rgb(107,195,245)' },
  { backgroundColor: 'rgb(115,253,234)', borderColor: 'rgb(98,215,199)' },
  { backgroundColor: 'rgb(137,250,78)', borderColor: 'rgb(116,213,67)' },
  { backgroundColor: 'rgb(255,243,89)', borderColor: 'rgb(218,214,87)' },
  { backgroundColor: 'rgb(255,150,141)', borderColor: 'rgb(217,128,120)' },
  { backgroundColor: 'rgb(255,160,208)', borderColor: 'rgb(243,142,193)' },
  { backgroundColor: 'rgb(11,132,237)', borderColor: 'rgb(8,122,192)' },
  { backgroundColor: 'rgb(24,231,207)', borderColor: 'rgb(25,196,176)' },
  { backgroundColor: 'rgb(96,216,55)', borderColor: 'rgb(83,183,49)' },
  { backgroundColor: 'rgb(251,226,49)', borderColor: 'rgb(213,192,44)' },
  { backgroundColor: 'rgb(255,101,78)', borderColor: 'rgb(217,84,66)' },
  { backgroundColor: 'rgb(234,0,119)', borderColor: 'rgb(204,37,121)' },
  { backgroundColor: 'rgb(1,118,186)', borderColor: 'rgb(6,101,159)' },
  { backgroundColor: 'rgb(6,143,134)', borderColor: 'rgb(0,168,158)' },
  { backgroundColor: 'rgb(29,177,0)', borderColor: 'rgb(29,150,6)' },
  { backgroundColor: 'rgb(248,186,0)', borderColor: 'rgb(210,158,4)' },
  { backgroundColor: 'rgb(238,35,13)', borderColor: 'rgb(202,31,12)' },
  { backgroundColor: 'rgb(203,41,122)', borderColor: 'rgb(173,35,105)' },
  { backgroundColor: 'rgb(0,78,128)', borderColor: 'rgb(2,66,109)' },
  { backgroundColor: 'rgb(1,124,118)', borderColor: 'rgb(3,106,101)' },
  { backgroundColor: 'rgb(1,112,1)', borderColor: 'rgb(5,96,4)' },
  { backgroundColor: 'rgb(255,146,1)', borderColor: 'rgb(217,126,5)' },
  { backgroundColor: 'rgb(180,23,0)', borderColor: 'rgb(154,21,4)' },
  { backgroundColor: 'rgb(153,25,94)', borderColor: 'rgb(130,22,80)' },
  { backgroundColor: 'rgb(214,213,213)', borderColor: 'rgb(182,181,181)' },
  { backgroundColor: 'rgb(146,146,146)', borderColor: 'rgb(124,124,124)' },
  { backgroundColor: 'rgb(95,95,95)', borderColor: 'rgb(80,80,80)' },
])
const color = computed(() => {
  return (
    (hexToRgb(formatMap.value.color) as string) ||
    defaultColorConfig.backgroundColor
  )
})

const addUsedColor = (item: ColorConfig) => {
  if (usedColorList.find((el) => el.backgroundColor === item.backgroundColor)) {
    return
  } else {
    const _item = colorConfigList.find(
      (el) => el.backgroundColor === item.backgroundColor
    )
    _item && usedColorList.unshift(_item)
  }
}

// 返回的颜色是 哈希值，需要转换为rgb颜色值
const changeColor = (item: ColorConfig) => {
  QuillEditor.value!.focus()
  // QuillEditor.value!.format('color', item.backgroundColor)

  const retainList: { len: number; attributes?: StringMap }[] = []
  const selection = QuillEditor.value!.getSelection()!
  if (selection.length) {
    // 选中的富文本内容
    const selectionDeltas = QuillEditor.value!.getContents(
      selection.index,
      selection.length
    )
    retainList.push({ len: selection.index })

    // 处理选区内的内容，如果insert是string，且非link，则同步加粗状态
    selectionDeltas?.forEach((delta) => {
      const { insert, attributes } = delta
      let _len = 1
      let _attributes
      if (typeof insert !== 'string') {
        _len = 1
        _attributes = attributes
      } else if (attributes?.link) {
        _len = insert.length
        _attributes = attributes
      } else {
        _len = insert.length
        _attributes = Object.assign(attributes || {}, {
          color: item.backgroundColor,
        })
      }
      retainList.push({ len: _len, attributes: _attributes })
    })

    const newDelta = new Delta()
    retainList.forEach((item) => {
      newDelta.retain(item.len, item.attributes)
    })
    QuillEditor.value?.updateContents(newDelta)
  } else {
    let _end = false
    const deltas = QuillEditor.value?.getContents()
    // 遍历找到光标的位置对应的内容
    let _checkLen = 0
    deltas?.forEach((delta) => {
      const { insert, attributes } = delta
      let _len = 0
      if (typeof insert !== 'string') _len = 1
      else _len = insert.length
      if (_end) return
      if (_checkLen > selection.index) return
      if (_checkLen < selection.index && _checkLen + _len >= selection.index) {
        // 说明光标在当前的delta
        if (attributes?.link) {
          _end = true
          return
        } else {
          QuillEditor.value!.format('color', item.backgroundColor)
        }
      }
      _checkLen += _len
    })
  }

  addUsedColor(item)
  getSelectionFormat()
}
</script>
<style lang="scss" scoped></style>
